package com.coursehub.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import reactor.core.publisher.Mono;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends AbstractGatewayFilterFactory<JwtAuthenticationFilter.Config> {
    
    @Value("#{'${app.security.permit-all-paths}'.split(',')}")
    private List<String> permitAllPaths;
    
    public JwtAuthenticationFilter() {
        super(Config.class);
    }
    
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            
            // 检查是否为免认证路径
            for (String permitPath : permitAllPaths) {
                if (path.matches(permitPath.replace("**", ".*"))) {
                    // 免认证路径，直接放行
                    return chain.filter(exchange);
                }
            }
            
            // 需要认证的路径，检查JWT token
            String authHeader = request.getHeaders().getFirst("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                // 没有token，返回401
                exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            
            // 有token，继续处理
            return chain.filter(exchange);
        };
    }
    
    public static class Config {
        // 配置类，可以添加自定义配置参数
    }
}